#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
"""
from uuid import uuid4
import base64
from binascii import crc32
import urllib
import urllib2

from google.appengine.ext import db
from django.utils import simplejson

from net4.common.util import int_to_s


def _safeurl(url):
    data = {'key': '789205680'}
    data['g'] = str(uuid4())
    url = base64.urlsafe_b64encode(url)
    data['s'] = crc32('%s%s%s' % (url, data['g'], '123123'))
    request_url = 'http://api.pc120.com/urlsafe/%s/json/?%s' % (url, urllib.urlencode(data))
    try:
        response = urllib2.urlopen(request_url)
    except:
        return None
    content = response.read()
    r = simplejson.loads(content)
    return r[0]

class URL(db.Model):
    """"""
    tiny = db.StringProperty('tiny_url')
    url = db.LinkProperty('url')
    created = db.DateTimeProperty('发布时间', auto_now_add=True) 
    last_modified = db.DateTimeProperty('最后修改时间', auto_now=True)
    user = db.UserProperty('user')
    title = db.StringProperty('title')
    description = db.TextProperty('desc')
    tiny_count = db.IntegerProperty('tiny count', default=1)
    redirect_count = db.IntegerProperty(default=0)
    type = db.IntegerProperty(default=1)
    hit_url = db.StringProperty('hit_url')
    
    def verify(self):
        r = _safeurl(self.url)
        if r:
            self.type = r['type']
            self.hit_url = r['hit_key']
    
    def put(self):
        super(URL, self).put()
        if not self.tiny:
            self.tiny = int_to_s(self.key().id())
            self.put()